<template>
  <div class="header">
    <div class="ai-status">{{ fileManagementStore.getSseLoadText }}</div>
    <div class="docx-title">{{ removeSuffix(docxTitle) }}</div>
    <div class="user-harder">
      <el-button :disabled="xlsxDisabled" @click="toXlsx"> 查看数据表 </el-button>
      <el-button @click="handleUpload">重新上传</el-button>
      <el-button disabled>历史记录</el-button>
    </div>
  </div>
  <el-container>
    <div class="left scrollbar">
      <div class="menu">项目摘要表</div>
      <NotData v-show="!docxContents" />
      <div id="docxMenu" class="menu-list" v-html="docxContents" @click="menuScroll"></div>
    </div>
    <div class="main scrollbar" ref="main">
      <LeftMain :documentContent="documentContent" @getTitle="getTitle" />
    </div>
    <div class="right">
      <RightMain ref="refRightMain" :data="accumulator" :fileName="fileName" />
    </div>
  </el-container>
  <div class="defunct-box" v-if="!isUpload">
    <div class="bg-box">
      <div class="update">
        <div class="update-box">
          <el-upload drag :before-upload="beforeUpload" :show-file-list="false" accept=".docx">
            <img src="@/imgs/Group4.png" alt="" />
            <h6>将文件拖拽至此处，或<span>点击上传</span> <span class="load-temple" @click.stop="">
              <a href="/file/pengwei-temple.docx" download>下载模板</a>
            </span></h6>
            <p class="text">*支持.docx等格式</p>
          </el-upload>
        </div>

        <div class="file-box" v-show="docxTitle">
          <span>{{ docxTitle }}</span>
          <el-button @click="handleAnalysis"> 开始解析 </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref} from 'vue'
import LeftMain from './components/leftMian.vue'
import RightMain from './components/rightMian.vue'
import fileManagement from '@/stores/fileManagement'
import { useRouter } from 'vue-router'
import { upload, uploadPython } from '@/api/pengwei/file'
import { ElMessage } from 'element-plus'
// import { getMsg } from '@/mock/index'
import { fileSuffix } from '@/utils/const'
import { removeSpaces, scrollIntoView } from '@/utils/tool'
import loading from '@/stores/loading'

const docxContents = ref('')
const docxTitle = ref('')
const accumulator = ref<any[]>([])
const documentContent = ref<any>('')
const main: any = ref(null)
const xlsxDisabled = ref(true)
const fileManagementStore = fileManagement()
const loadingStore = loading()
const router = useRouter()
const refRightMain: any = ref(null)
const fileName = ref('')
const isUpload = ref(false)
let file: any = null
let pythonDocxFileName = ref('')

function getTitle({ html }: { html: string; el: Element }) {
  docxContents.value = html
}

function toXlsx() {
// window.open(window.location.origin+'/fileManagement/preview-xlsx-file?name=11122-6.xlsx', '_blank')
  // const url = router.resolve({ path: `/fileManagement/preview-xlsx-file` }).href+`?name=${pythonDocxFileName.value}`
  const url = router.resolve({ name: 'PengweiPreviewXlsx' }).href+`?name=${pythonDocxFileName.value}`
  console.log(url, 'url')
  window.open(url, '_blank')
  console.log('查看数据表');
}

// 点击标题跳转到指定位置
function menuScroll(e: any) {
  const arr = e.target.parentNode.children
  const text = e.target.innerText
  const pList = main.value.querySelectorAll('p')
  let isScroll = false
  for (let i = 0; i < arr.length; i++) {
    const p = arr[i]
    p.classList.remove('active')
  }
  e.target.classList.add('active')
  for (let i = 0; i < pList.length; i++) {
    const p = pList[i];
    if(removeSpaces(p.innerText) === removeSpaces(text)) {
      isScroll = true
      scrollIntoView(p)
    }
  }
  if(!isScroll) {
    ElMessage.error('标题跳转匹配失败')
  }
}

function removeSuffix(name: string) {
  if (!name) return ''
  const title = name.substring(0, name.lastIndexOf('.docx'))
  return title
}

function beforeFile(f: File) {
  if (/\s/.test(f.name)) {
    ElMessage.error('文件名中不能包含空格')
    return
  }
  docxTitle.value = f.name
  documentContent.value = f
  uploadFile(f)
}

function handleUpload() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.docx'
  input.click()
  input.addEventListener('change', (e: any) => {
    const f = e.target.files[0]
    beforeFile(f)
  })
}

async function uploadFile(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  loadingStore.updatedLoading(true)
  xlsxDisabled.value = true

  // 上传到java服务
  upload(formData)
    .then((res: any) => {
      const { status, data } = res
      if (status !== 200 || !data) return ElMessage.error('文件上传失败')
      isUpload.value = true
      refRightMain.value.getDocxData(data)
    })
    .catch(() => {
      docxTitle.value = ''
    })
    .finally(() => loadingStore.updatedLoading(false))

  // 上传到python服务
  uploadPython(formData).then((res: any) => {
    if(res.status === 200) {
      const { data } = res
      console.log(data, 'data=123');

      if(data && data.message && data.message.includes(fileSuffix.docx)) {
        ElMessage.success('文件上传成功')
        xlsxDisabled.value = false
        pythonDocxFileName.value = data.message.replace(fileSuffix.docx, fileSuffix.xlsx)
        console.log(pythonDocxFileName, 'pythonDocxFileName');
      }
    }
  })
}

function beforeUpload(f: any) {
  docxTitle.value = f.name
  file = f
  return false
}

function handleAnalysis() {
  if (!file || file.name.indexOf('.docx') < 0) {
    ElMessage.error('只支持.docx类型的文件')
    return
  }
  beforeFile(file)
}
</script>

<style scoped lang="scss">
$headHeight: 50px;
$headMarginBottom: 0px;
$paging20: 10px;
.el-container {
  width: 100%;
  height: calc(100% - $headHeight - $headMarginBottom);
}
.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $headMarginBottom;
  height: $headHeight;
  padding: 0 $paging20;
  border-bottom: 1px solid #f5f5f5;
  .ai-status {
    font-size: 14px;
    color: #4466f0;
  }
  .docx-title {
    color: #000;
    font-size: 16px;
  }
  .user-harder {
    button {
      background: #4466f0;
      color: #fff;
    }
  }
}
.left {
  width: 280px;
  min-width: 280px;
  height: 100%;
  background-color: #fff;
  // margin-right: 10px;
  overflow-y: auto;
  position: relative;
  display: inline-block;
  .menu {
    height: 30px;
    line-height: 30px;
    text-align: left;
    font-size: 14px;
    font-weight: bold;
    padding-left: 10px;
    color: #5a78f2;
    display: flex;
    align-items: center;
  }
  .menu-list {
    padding: 10px;
    padding-right: 0;
    :deep(.item) {
      display: flex;
      line-height: 30px;
      align-items: center;
      cursor: pointer;
      font-size: 13px;
      padding: 0 10px;
      margin-bottom: 4px;
      &.active,
      &:hover {
        // border-color: #4466f0;
        color: #4466f0;
        background: rgba(68, 102, 240, 0.2);
      }
    }
  }
}
.main {
  // width: 57.6%;
  flex: 1;
  height: 100%;
  margin: 0 20px 0 0 ;
  overflow-y: auto;
  overflow-x: auto;
  display: flex;
  justify-content: center;
  background: #f3f4f4;
}
.right {
  width: 360px;
  min-width: 360px;
  height: 100%;
  background-color: #fff;
}

.leftPane {
  display: flex;
  width: 100%;
  height: 100%;
}
ul {
  list-style-type: none;
  padding-left: 20px;
}

li {
  margin: 5px 0;
  cursor: pointer;
}

li div {
  padding: 5px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

li div:hover {
  background-color: #e0e0e0;
}
.defunct-box {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #f3f4f4;
  padding: 20px;
  z-index: 2;
  .bg-box {
    width: 100%;
    height: 100%;
    // background: #fff;
    background: url('@/imgs/Group5.jpg') no-repeat center center;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;
    user-select: none;
    .update {
      display: flex;
      flex-direction: column;
      align-items: center;
      user-select: none;
      .update-box {
        :deep(.el-upload) {
          user-select: none;
          .el-upload-dragger {
            border: none;
            background: transparent;
            padding: 0;
            user-select: none;
          }
        }
      }
      img {
        width: 200px;
      }
      h6 {
        color: #000;
        font-size: 14px;
        margin: 10px 0 0 0;
        span {
          color: #4466f0;
          cursor: pointer;
          &.load-temple{
            a{
              color: #666;
            }
            color: #666;
          }
        }
      }
      .text {
        text-align: center;
        margin-top: 2px;
        color: #666;
      }
      .file-box {
        width: 600px;
        height: 60px;
        background: #fff;
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;
        button {
          background: #4466f0;
          color: #fff;
        }
      }
    }
  }
}
.update-loading {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  .loading-container {
    width: 300px;
    height: 300px;
    border-radius: 15px;
    background: #dbdfed;
    display: flex;
    justify-content: center;
    align-items: center;

    span {
      width: 100%;
    }
    :deep(.el-loading-mask) {
      circle {
        stroke: #4466f0;
      }
      .el-loading-text {
        color: #4466f0;
      }
    }
  }
}
</style>
